﻿using System;
using Game.Terrain;
using UnityEditor;
using UnityEngine;
using UnityEngine.Tilemaps;

namespace Game.TerrainEditor
{
    [CustomEditor(typeof(MapEntityBase))]
    public class MapEntityBaseEditor :  TileBaseEditor
    {
        protected MapEntityBase EntityTile => target as MapEntityBase;

        protected virtual string IconPath { get; set; }
            = "Assets/Editor/Editor Resources/Icon/tile.png";

        private Texture2D cachedPreviewTexture;

        public virtual void OnEnable()
        {
            //SetIcon();
        }

        public virtual void SetIcon()
        {
            cachedPreviewTexture = AssetDatabase.LoadAssetAtPath<Texture2D>(IconPath);
            // 设置自定义图标
            if (cachedPreviewTexture)
            {
                EditorGUIUtility.SetIconForObject(EntityTile, cachedPreviewTexture);
                EditorApplication.RepaintProjectWindow(); // 刷新项目窗口
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
            }
        }

        public override void OnInspectorGUI()
        {
            // 调用基类的 Inspector 绘制方法，显示默认的 Tile 属性
            base.OnInspectorGUI();

            // 添加自定义属性的绘制逻辑
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("实体属性", EditorStyles.boldLabel);
            EntityTile.entityId = EditorGUILayout.TextField("实体 ID", EntityTile.entityId);
            EntityTile.entityType = (MapEntityBase.EntityType)EditorGUILayout.EnumPopup("实体类型", EntityTile.entityType);

            // 如果修改了属性，标记为脏以保存更改
            if (GUI.changed)
            {
               // SetIcon();
                Undo.RecordObject(EntityTile, "Modify MapEntityBase");
                EditorUtility.SetDirty(EntityTile); // 兼容旧版本
            }
        }

        // private void OnDisable()
        // {
        //     // 清理资源
        //     if (cachedPreviewTexture != null)
        //     {
        //         Resources.UnloadAsset(cachedPreviewTexture);
        //         cachedPreviewTexture = null;
        //     }
        // }
    }
}